import { ElNotification } from 'element-plus'
import { useAdminInfo } from '/@/stores/adminInfo'
import WebSocketService from '/@/utils/shop/webSocketService'
import { ref } from 'vue'
import { handleMessage } from '/@/api/backend/shop/notify/notify'
import '/@/components/shop/notify/wsNotify.scss'
import { fullUrl } from '/@/utils/common'
import { useShopConfig } from '/@/stores/shop/shopConfig'

let checkQueueTimer: NodeJS.Timer | undefined | null

const messageQueue = ref<any[]>([])
const isNotify = ref(false)

// websocket端口号
const wsPort = 2828

const currentUrl = new URL(window.location.href)
const protocol = currentUrl.protocol === 'https:' ? 'wss' : 'ws'
let websocketUrl = `${protocol}://${currentUrl.hostname}:${wsPort}`

if (protocol === 'wss') {
    websocketUrl = `${protocol}://${currentUrl.hostname}/${protocol}}`
}

export const connectWebSocket = async () => {
    const ws = new WebSocketService(websocketUrl)
    const adminInfo = useAdminInfo()

    // 设置音频播放状态
    useShopConfig().state.playAudio = false

    ws.onOpen = () => {
        ws.sendMessage({
            pathInfo: 'shop/worker.notify/bind',
            ba_token: adminInfo.getToken(),
        })
    }

    ws.handleMessage = (message) => {
        const data = message.data
        switch (message.type) {
            case 'bind':
                console.log(`成功连接到服务器`)
                break
            case 'notify':
                if (data.unread_count) {
                    useShopConfig().state.unreadCount = data.unread_count
                }
                if (data.message) {
                    onHandleNotify(data.message)
                }
                break
        }
    }
}

const onHandleNotify = (data: any) => {
    messageQueue.value.push(data)

    if (isNotify.value) {
        if (!checkQueueTimer) {
            checkQueueTimer = setInterval(checkAndNotify, 3000)
        }
    } else {
        checkAndNotify()
    }
}

//检查消息队列并触发通知
const checkAndNotify = () => {
    if (messageQueue.value.length <= 0) {
        clearInterval(checkQueueTimer as any)
        checkQueueTimer = null
        isNotify.value = false
        return
    }

    const data = messageQueue.value.shift()
    if (data) {
        onNotify(data)

        if (useShopConfig().state.playAudio && data.audio_path) {
            playNotificationAudio(data.id, fullUrl(data.audio_path))
        }
    }
}

const onNotify = (data: any) => {
    const notifyInstance = ElNotification({
        icon: 'el-icon-Bell',
        title: data.message_type_map[data.message_type],
        message: data.message,
        position: 'bottom-right',
        customClass: 'custom-notify',
        onClick: () => {
            handleMessage(data.id, data.message_type, data.message_data)
            notifyInstance.close()
            // 移除已被点击的消息提醒
            audioQueue.value = audioQueue.value.filter((item) => item.id !== data.id)
        },
    })
    isNotify.value = true
}

// 音频播放队列
const audioQueue = ref<{ id: number; path: string }[]>([])
const isPlaying = ref(false)

function playNextAudio() {
    if (audioQueue.value.length === 0 || isPlaying.value) {
        return
    }

    const { path } = audioQueue.value.shift()!
    if (!path) return

    isPlaying.value = true // 设置正在播放状态

    let audio: HTMLAudioElement | null = new Audio(fullUrl(path))

    audio.onended = () => {
        setTimeout(() => {
            isPlaying.value = false
            if (audio) {
                // 暂停并移除当前音频
                audio.pause()
                audio = null
            }
            // 播放下一个音频
            playNextAudio()
        }, 100)
    }

    audio.play().catch((error) => {
        console.error('Failed to play notification sound:', error)
        isPlaying.value = false
    })
}

// 播放通知音频
function playNotificationAudio(id: number, path: string) {
    // 当前正在播放，将新音频加入队列
    audioQueue.value.push({ id, path })
    if (!isPlaying.value) {
        playNextAudio()
    }
}

export const connectNotify = () => {
    if (useShopConfig().state.notify) {
        connectWebSocket()
    }
}
